package com.batchengine.task;

import static com.batchengine.DataAdapter.FILE;
import com.batchengine.Definitions;
import static com.batchengine.Definitions.ContextParams.*;
import static com.batchengine.Definitions.TaskType.PERL;
import static com.batchengine.Definitions.TaskType.PYTHON;
import static com.batchengine.task.TaskParser.getTaskDataParser;
import static com.batchengine.util.EnvUtil.createObjectz;

import static java.util.Collections.synchronizedMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by  solutions
 * Author: sunil.incubator@yahoo.com
 * Date: Jul 25, 2009
 */
public final class TaskContext {

    private Map<Definitions.ContextParams, Object> contextMap = synchronizedMap(new HashMap<Definitions.ContextParams, Object>(5));

    private TaskContext() {
    }

    public void addcontextParam(Definitions.ContextParams param, Object value) {
        contextMap.put(param, value);
    }

    public Object getContextParam(Definitions.ContextParams param) {
        return contextMap.get(param);
    }

    public static TaskContext createTaskContext(Long taskId) {

        TaskContext context = new TaskContext();

        if (null == taskId) {
            return context;
        }
        TaskInfo taskInfo = getTaskDataParser(FILE).getTaskConfigurationMap().get(taskId);

        if (null == taskInfo) {
            return context;
        }

        String clazzName = taskInfo.getClazzName();
        if (PYTHON.equals(taskInfo.getTaskType())) {
            clazzName = PythonTask.class.getName();
        } else if (PERL.equals(taskInfo.getTaskType())) {
            clazzName = PythonTask.class.getName();
        }
        context.addcontextParam(TASK_ID, taskId);
        context.addcontextParam(TASK_TYPE, taskInfo.getTaskType());
        context.addcontextParam(TASK_CLASS, clazzName);
        context.addcontextParam(TASK_SELECTOR, taskInfo.getSelctorClazz());
        context.addcontextParam(TASK_STOP_SIGNAL, taskInfo.getSignalClazz());
        context.addcontextParam(TASK_INSTANCE, createObjectz(clazzName));

        return context;
    }

    public String toString() {

        Set<Definitions.ContextParams> contextParamsSet = contextMap.keySet();
        StringBuilder sb = new StringBuilder("[").append("\n");
        for (Definitions.ContextParams contextParams : contextParamsSet) {
            sb.append(String.format("%s=%s\n", contextParams, contextMap.get(contextParams)));
        }
        sb.append("]");
        return sb.toString();
    }
}
